const  express = require('express');
const router = require('./router/api');
const cors = require('cors');
const socketIO = require('socket.io');
const http = require('http');
const message = require("./model/message");

const  app=express();
app.use(cors());
app.use(express.json())
app.use(express.static('public'))
app.use(express.urlencoded({extended:false}))
app.use('/',router)
const server = http.createServer(app);


server.listen(8081,()=>{
    console.log('http://localhost:8081')
})

const io = socketIO(server,{
    cors: {
        origin: '*'
    }
});
// const io = new Server(server);
io.on('connection', (socket) => {
    console.log('A user connected');

    // 监听加入房间事件
    socket.on('joinRoom', (room) => {
        console.log(`User ${socket.id} joined room ${room}`);
        socket.join(room); // 加入房间
    });

    // 监听消息发送事件
    socket.on('sendMessage', (data) => {
        // console.log(`Message received in room ${data.room}: ${data.message}`);
        console.log(data)
        io.to(data.roomname).emit('message', data);// 发送消息给指定房间的所有用户
        const result=message.create(data)
        if(result!=null)
        {
            console.log('消息已存入数据库')
        }
    });


    // 监听断开连接事件
    socket.on('disconnect', () => {
        console.log('A user disconnected');
    });
});
